﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameFramework.common;
using GameFramework.UI;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace Editor.ConfigExport.UI
{
    public class ExcelExportCtl:BaseView
    {
        [UIBind(ClassName = "pathField")]
        public TextField pathField;//excel文件所在路径的展示
        [UIBind(ClassName = "openFileBtn")]
        public Button openFileBtn;//打开文件夹选择excel表格路径的按钮
        [UIBind(ClassName = "fileList")]
        public ListView fileList;//文件预览按钮

        [UIBind(Name = "selectAll")]
        public Toggle selectAll;//全选
        [UIBind(Name = "selectNone")]
        public Toggle selectNone;//全不选
        
        [UIBind(Name = "export")]
        public Button export;//导出数据按钮

        private List<FileInfo> toshowFiles = new List<FileInfo>();
        private VisualTreeAsset fileItemAsset;
        private ExcelExportConfig _config;
        

        private HashSet<FileInfo> exportFileList = new HashSet<FileInfo>();
        public override void init()
        {
            base.init();
            _config = AssetDatabase.LoadAssetAtPath<ExcelExportConfig>(
                "Assets/Editor/ConfigExport/config/ExportConfig.asset");
            // Debug.Log(fileList);
            // if (_config.excelFolderPath.Equals(""))//路径为空，未设置，则设置成默认值
            // {
            //     _config.excelFolderPath = Application.dataPath + "/AdressableResource/excel_configs";
            // }

            pathField.value = _config.excelFolderPath;
            getConfigFiles();
            openFileBtn.RegisterCallback<ClickEvent>(evt =>
            {
                string folder = EditorUtility.OpenFolderPanel("选择配置文件夹","","");
                exportFileList.Clear();//文件路径变化了，导出列表清空
                updateExcelConfigPath(folder);
                getConfigFiles();
            });
            //文件显示列表初始化
            fileListInit();
            //全选处理
            selectAllHandle();
            //全不选处理
            selectNoneHandle();
            //正式导出处理
            exportHandle();

        }

        private void exportHandle()
        {
            export.RegisterCallback<ClickEvent>(e =>
            {
                //TODO 0.先将excel转成csv文件 使用库
                //https://github.com/ExcelDataReader/ExcelDataReader
                //参考：https://blog.csdn.net/u014361280/article/details/103510451
                //1.根据选择的文件，复制文件到临时目录，改名.csv.bytes
                string[] files = Directory.GetFiles(_config.excelFolderPath);
                string tempPath = _config.excelFolderPath+"/temp";
                Directory.Delete(tempPath,true);
                Directory.CreateDirectory(tempPath);
                foreach (string fileName in files)
                {
                    File.Copy(fileName,tempPath+"/"+Path.GetFileNameWithoutExtension(fileName)+".csv",true);
                }
                //2.加载bytes文件封装文本流，第一行表头由反射生成实体类
                //3.加载生成的实体类
                //3.变量文件所有行，逐行解析生成实体类实例，并写入到对应的asstes文件
                Debug.Log("导出文件数量："+exportFileList.Count);
                foreach (FileInfo fileInfo in exportFileList)
                {
                    Debug.Log(fileInfo.FullName);
                }
            });

        }

        private void selectNoneHandle()
        {
            selectNone.RegisterCallback<ChangeEvent<bool>>(e =>
            {
                if (e.newValue)
                {
                    List<VisualElement> items = fileList.Query<VisualElement>(className:"item").ToList();
                    foreach (VisualElement element in items)
                    {
                        Toggle toggle = element.Q<Toggle>();
                        toggle.value = false;
                    }

                    selectAll.value = false;
                    exportFileList.Clear(); 
                }
            });

        }

        private void selectAllHandle()
        {
            selectAll.RegisterCallback<ChangeEvent<bool>>(e =>
            {

                if (e.newValue)
                {
                    List<VisualElement> items = fileList.Query<VisualElement>(className:"item").ToList();
                     foreach (VisualElement element in items)
                     {
                         Toggle toggle = element.Q<Toggle>();
                         toggle.value = true;
                     }
                     selectNone.value = false;
                    //将文件夹中的所有文件加入到导出列表
                    exportFileList.UnionWith(toshowFiles);
                }
            });

        }

        private void fileListInit()
        {
            // fileList.fixedItemHeight = 40;
            
            fileList.bindItem = (element, i) =>
            {
                initFileItem(element,i);
            };
            fileList.makeItem = () =>
            {

                if (fileItemAsset == null)
                {
                    fileItemAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/ConfigExport/UI/FileItem.uxml");
   
                }

                if (fileItemAsset == null)
                {
                    return null;
                }

                VisualElement instance = fileItemAsset.Instantiate();

                return instance;
            };
            //双击item,e里包含的是事件源对象，
            fileList.itemsChosen += (e) =>
            {
                FileInfo o = e.ToList()[0] as FileInfo;
                int index = toshowFiles.IndexOf(o);
                UQueryBuilder<VisualElement> query = fileList.Query<VisualElement>(className: "item");
                VisualElement element = query.ToList()[index];
                Toggle toggle = element.Q<Toggle>();
                if (toggle.value)
                {
                    exportFileList.Remove(o);
                }
                else
                {
                    exportFileList.Add(o);
                }

                toggle.value = !toggle.value;
            };

            fileList.itemsSource = toshowFiles;

        }

        private void initFileItem(VisualElement instance, int i)
        {
            //文件名赋值
            Label fileNameLabel = instance.Q<Label>();
            fileNameLabel.text = toshowFiles[i].Name;
            //绑定事件
            Toggle select = instance.Q<Toggle>();
            select.userData = toshowFiles[i];
            select.RegisterCallback<ChangeEvent<bool>>(evt =>
            {
                if (evt.newValue)//选中
                {
                    FileInfo data = select.userData as FileInfo;
                    exportFileList.Add(data);
                }
                else
                {
                    FileInfo data = select.userData as FileInfo;
                    exportFileList.Remove(data);
                }
            });
        }

        private void getConfigFiles()
        {
            string folderPath = _config.excelFolderPath;
            // Debug.Log("文件夹路径："+folderPath);
            if (folderPath == null || folderPath.Equals(""))
            {
                return;
            }
            //TODO 读取文件列表
            DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
            if (!directoryInfo.Exists)
            {
                Debug.LogError("配置文件夹路径不存在："+folderPath);
                return;
            }
            toshowFiles.Clear();
            toshowFiles.AddRange(directoryInfo.GetFiles());
            fileList.RefreshItems();
            Debug.Log("文件数："+toshowFiles.Count);
            // foreach (FileInfo fileInfo in files)
            // {
            //     Debug.Log(fileInfo.Name);
            // }
        }

        public void updateExcelConfigPath(string newPath)
        {
            if (newPath == null || newPath.Equals(""))
            {
                return;
            }
            _config.excelFolderPath = newPath;
            pathField.value = newPath;
        }
    }
}